package com.dc.chat.websocket;

import com.dc.chat.entity.redisCatch.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

@Component
public class LoginHandshakeInterceptor implements HandshakeInterceptor {
    @Resource
    RedisTemplate redisTemplate;
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {

        ServletServerHttpRequest servletServerHttpRequest=(ServletServerHttpRequest) serverHttpRequest;
        HttpServletRequest request = servletServerHttpRequest.getServletRequest();
        String admin = request.getParameter("admin");
        if(admin==null){
            String token = request.getParameter("token");
            Jws<Claims> jws = Jwts.parser().setSigningKey("abcdef").parseClaimsJws(token);
            Claims body = jws.getBody();
            String username = (String) body.get("username");
            LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get("login#0#" + username + "#" + token);
            if(loginUser!=null){
                redisTemplate.delete("login#0#" + username + "#" + token);
                redisTemplate.opsForValue().set("login#1#"+username+"#"+token,loginUser);
                map.put("key","login#1#"+username+"#"+token);
                map.put("username",username);
                map.put("token",token);
                return true;
            }else{
                return false;
            }
        }else{
            String o = (String) redisTemplate.opsForValue().get(admin);
            if("admin".equals(o)){
                map.put("admin",admin);
                return true;
            }else{
                return false;
            }
        }

    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        System.out.println("握手成功");
    }
}
